<template>
  <base-load-page
    :loadState="pageLoad.loadState"
    :description="pageLoad.description"
    :pageLoadButton="[{ text: '重新加载', callBack: () => getBaseDataAxios() }]"
    class="base-load-page"
  >
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <bubble-select-local
            v-model="filterData.templateType"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
              { label: '全部商品', value: '' },
              { label: '充值K币', value: 1 },
              { label: '充值VIP', value: 2 },
              { label: '解锁短剧', value: 4 },
            ]"
            placeholder="请选择模板类型"
            @change="getBaseDataAxios(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.isDefault"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
              { label: '全部模版', value: '' },
              { label: '默认模版', value: 1 },
              { label: '非默认模版', value: 0 },
            ]"
            placeholder="请选择是否默认模版"
            @change="getBaseDataAxios(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.templateName"
            clearable
            placeholder="请输入模板名称"
            style="width: 100%"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getBaseDataAxios(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconPlus" @click="handleAdd">新增</el-button>
        </div>
      </div>
    </template>
    <div style="width: 100%; height: 100%; overflow: hidden">
      <el-scrollbar v-if="baseData">
        <div class="module-list">
          <div v-for="template in tableData" :key="template.productTemplateId" class="module-item">
            <page-simulation-template :selectIndex="template.selectIndex" :templateProductList="template.productList"></page-simulation-template>
            <div style="display: flex; flex: 1; flex-direction: column; padding: 15px 10px 0">
              <div class="info-box">
                <div class="title-box">
                  <span class="title">{{ template.templateName }}</span>
                </div>
                <div style="display: flex; flex-direction: column">
                  <el-tag v-if="template.templateType === 1" key="tag-1" type="primary">K币充值</el-tag>
                  <el-tag v-else-if="template.templateType === 2" key="tag-2" type="warning">会员充值</el-tag>
                  <el-tag v-else-if="template.templateType === 4" key="tag-3" type="success">播放解锁</el-tag>
                  <template v-if="template.isDefault === 1">
                    <el-tag v-if="template.isFirstRecharge === 1" key="tag-4" class="violet-tag">复购默认</el-tag>
                    <el-tag v-else key="tag-5" class="cyan-tag">首充默认</el-tag>
                  </template>
                </div>
              </div>
              <div class="button-box">
                <el-button class="butt" :icon="IconEdit" type="primary" @click="handleEdit(template)">编辑</el-button>
                <el-button
                  v-if="template.isDefault !== 1 && template.wxFinderFlag !== 1"
                  class="butt"
                  :icon="IconDelete"
                  type="danger"
                  @click="handleDel(template.productTemplateId!)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="pageLoad.loadState === true"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getBaseDataAxios(true)"
        ></el-pagination>
      </div>
    </template>
    <page-pay-template-info ref="pagePayTemplateInfoRef"></page-pay-template-info>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconPlus from '~icons/ep/plus';
  import IconEdit from '~icons/ep/edit';
  import IconDelete from '~icons/ep/delete';
  import {
    type ReferralTemplate,
    type ReferralTemplateListRequest,
    addReferralTemplateNewAxios,
    delReferralTemplateAxios,
    editReferralTemplateNewAxios,
    getReferralTemplateListNewAxios,
  } from '@/api/marketing-management';
  import BaseLoadPage from '@/components/base/base-load-page/base-load-page.vue';
  import PagePayTemplateInfo from '@/components/page/page-pay-template-info/page-pay-template-info.vue';

  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 总数量 */
    total: 0,
  });

  const pagePayTemplateInfoRef = ref<InstanceType<typeof PagePayTemplateInfo>>();
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  const filterData: Ref<ReferralTemplateListRequest> = ref<ReferralTemplateListRequest>({
    templateName: '',
    templateType: undefined,
    isDefault: undefined,
    current: 1,
    size: 40,
  });

  const tableData: Ref<ReferralTemplate[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    getBaseDataAxios();
  });
  onBeforeRouteLeave(() => {
    pagePayTemplateInfoRef.value?.hide();
  });

  /**
   * 设置表格数据
   */
  async function getBaseDataAxios(showLoading = true) {
    try {
      await nextTick();
      pageLoad.loadState = Boolean(showLoading);
      const res = await getReferralTemplateListNewAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      pageLoad.loadState = false;
      return Promise.resolve(true);
    } catch (error) {
      tableData.value = [];
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
      return Promise.reject(error);
    }
  }

  /** 新增价格模板 */
  function handleAdd() {
    pagePayTemplateInfoRef.value?.show({
      type: 'add',
      async submit(res) {
        try {
          await addReferralTemplateNewAxios(res);
          await getBaseDataAxios();
          ElToast.success('新增成功');
          return Promise.resolve(true);
        } catch (error) {
          ElToast.error('新增失败');
          return Promise.resolve(error);
        }
      },
    });
  }

  /** 编辑价格模板 */
  function handleEdit(row: ReferralTemplate) {
    pagePayTemplateInfoRef.value?.show({
      type: 'edit',
      referralTemplate: row,
      async submit(res) {
        try {
          await editReferralTemplateNewAxios(res);
          await getBaseDataAxios();
          ElToast.success('修改成功');
          return Promise.resolve(true);
        } catch (error) {
          ElToast.error(error.msg || '修改失败');
          return Promise.reject(error);
        }
      },
    });
  }

  /**
   * 删除
   */
  function handleDel(productTemplateId: number) {
    ElMessageBox.confirm('删除后不可恢复，您确定删除吗？', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          try {
            await delReferralTemplateAxios(productTemplateId);
            getBaseDataAxios();
            instance.confirmButtonLoading = false;
            done();
            ElToast.success('删除成功');
          } catch (error) {
            instance.confirmButtonLoading = false;
            ElToast.error(error.msg || '删除失败，-BD004');
          }
        } else {
          done();
        }
      },
    });
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }

  .module-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, 259px);
    grid-gap: 25px;
    padding-bottom: 15px;

    .module-item {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      background: $c-bg-block;
      border-radius: 10px;
      box-shadow: var(--my-box-shadow-fill);
    }

    .info-box {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: flex-start;
      padding-bottom: 15px;

      .title-box {
        display: flex;
        flex: 1;
        align-items: center;
        justify-content: flex-start;
        min-height: 38px;
        margin-right: 8px;

        .title {
          display: -webkit-box;
          overflow: hidden;
          font-size: 16px;
          font-weight: bold;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          line-clamp: 2;
        }
      }
    }

    .button-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 15px;

      .butt {
        width: 100%;
      }
    }
  }

  .violet-tag {
    --el-tag-text-color: var(--el-color-violet);
    --el-tag-bg-color: var(--el-color-violet-light-9);
    --el-tag-border-color: var(--el-color-violet-light-8);
    margin-top: 4px;
  }

  .cyan-tag {
    --el-tag-text-color: var(--el-color-cyan);
    --el-tag-bg-color: var(--el-color-cyan-light-9);
    --el-tag-border-color: var(--el-color-cyan-light-8);
    margin-top: 4px;
  }
</style>
